#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/mm.h>

#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/memory.h>
#include <asm/tlbflush.h>
#include <asm/thread_info.h>
#include <asm/mmu_context.h>

#define BUS_ADRALN 0
#define SEGV_MAPERR 0
#define SEGV_ACCERR 0
#define BUS_OBJERR 0

#define user_mode(regs)	\
	(((regs)->ARM_cpsr & 0xf) == 0)

/*
 * Fault status register encodings.  We steal bit 31 for our own purposes.
 */
#define FSR_LNX_PF		(1 << 31)
#define FSR_WRITE		(1 << 11)
#define FSR_FS4			(1 << 10)
#define FSR_FS3_0		(15)

static inline int fsr_fs(unsigned int fsr)
{
	return (fsr & FSR_FS3_0) | (fsr & FSR_FS4) >> 6;
}

/*
 * Oops.  The kernel tried to access some page that wasn't present.
 */
static void __do_kernel_fault(struct mm_struct *mm, unsigned long addr, unsigned int fsr,
		  struct pt_regs *regs)
{
	// /*
	//  * Are we prepared to handle this kernel fault?
	//  */
	// if (fixup_exception(regs))
	// 	return;

	/*
	 * No handler, we'll have to terminate things with extreme prejudice.
	 */
	// bust_spinlocks(1);
	printf(
		"Unable to handle kernel %s at virtual address %08lx\r\n",
		(addr < PAGE_SIZE) ? "NULL pointer dereference" :
		"paging request", addr);
	while (1);

	// show_pte(mm, addr);
	// die("Oops", regs, fsr);
	// bust_spinlocks(0);
	// do_exit(SIGKILL);
}

/*
 * Something tried to access memory that isn't in our memory map..
 * User mode accesses just cause a SIGSEGV
 */
static void __do_user_fault(struct task_struct *tsk, unsigned long addr,
		unsigned int fsr, unsigned int sig, int code, struct pt_regs *regs)
{
// 	struct siginfo si;

// #ifdef CONFIG_DEBUG_USER
// 	if (user_debug & UDBG_SEGV) {
		printf("%s: unhandled page fault (%d) at 0x%08lx, code 0x%03x\r\n",
		       tsk->comm, sig, addr, fsr);
// 		show_pte(tsk->mm, addr);
// 		show_regs(regs);
// 	}
// #endif

	while (1);

// 	tsk->thread.address = addr;
// 	tsk->thread.error_code = fsr;
// 	tsk->thread.trap_no = 14;
// 	si.si_signo = sig;
// 	si.si_errno = 0;
// 	si.si_code = code;
// 	si.si_addr = (void __user *)addr;
// 	force_sig_info(sig, &si, tsk);
}

void do_bad_area(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
{
	struct task_struct *tsk = current;
	struct mm_struct *mm = tsk->active_mm;

	/*
	 * If we are in kernel mode at this point, we
	 * have no context to handle this fault with.
	 */
	if (user_mode(regs))
		__do_user_fault(tsk, addr, fsr, SIGSEGV, SEGV_MAPERR, regs);
	else
		__do_kernel_fault(mm, addr, fsr, regs);
}

#define VM_FAULT_BADMAP		0x010000
#define VM_FAULT_BADACCESS	0x020000

/*
 * Check that the permissions on the VMA allow for the fault which occurred.
 * If we encountered a write fault, we must have write permission, otherwise
 * we allow any permission.
 */
// static inline bool access_error(unsigned int fsr, struct vm_area_struct *vma)
// {
// 	unsigned int mask = VM_READ | VM_WRITE | VM_EXEC;

// 	if (fsr & FSR_WRITE)
// 		mask = VM_WRITE;
// 	if (fsr & FSR_LNX_PF)
// 		mask = VM_EXEC;

// 	return vma->vm_flags & mask ? false : true;
// }

#define FAULT_FLAG_WRITE 0

static int __do_page_fault(struct mm_struct *mm, unsigned long addr, unsigned int fsr,
		struct task_struct *tsk)
{
	struct vm_area_struct *vma;
	int fault;

	printf("this is %s(): %d >>> addr = 0x%x\r\n", __func__, __LINE__, addr);

	vma = find_vma(mm, addr);
	fault = VM_FAULT_BADMAP;
	if (!vma)
		goto out;
	if (vma->vm_start > addr)
		goto check_stack;

	printf("this is %s(): %d >>> vma->vm_start = 0x%x\r\n", __func__, __LINE__, vma->vm_start);
	printf("this is %s(): %d >>> vma->vm_end = 0x%x\r\n", __func__, __LINE__, vma->vm_end);
	printf("this is %s(): %d >>> vma->vm_pgoff = 0x%x\r\n", __func__, __LINE__, vma->vm_pgoff);
	if (vma->vm_file)
		printf("this is %s(): %d >>> vma->filename = %s\r\n", __func__, __LINE__, vma->vm_file->f_path.dentry->d_iname);

	/*
	 * Ok, we have a good vm_area for this
	 * memory access, so we can handle it.
	 */
good_area:
	// if (access_error(fsr, vma)) {
	// 	fault = VM_FAULT_BADACCESS;
	// 	goto out;
	// }

	/*
	 * If for any reason at all we couldn't handle the fault, make
	 * sure we exit gracefully rather than endlessly redo the fault.
	 */
	fault = handle_mm_fault(mm, vma, addr & PAGE_MASK, (fsr & FSR_WRITE) ? FAULT_FLAG_WRITE : 0);
	// if (fault & VM_FAULT_ERROR)
	// 	return fault;
	// if (fault & VM_FAULT_MAJOR)
	// 	tsk->maj_flt++;
	// else
	// 	tsk->min_flt++;
	return fault;

check_stack:
	// if (vma->vm_flags & VM_GROWSDOWN && !expand_stack(vma, addr))
	// 	goto good_area;
out:
	return fault;
}

static int do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
{
	printf("this is %s(): %d\r\n", __func__, __LINE__);
#if 1
	struct task_struct *tsk;
	struct mm_struct *mm;
	int fault, sig, code;

	// if (notify_page_fault(regs, fsr))
	// 	return 0;

	tsk = current;
	mm  = tsk->mm;

	/*
	 * If we're in an interrupt or have no user
	 * context, we must not take the fault..
	 */
	// if (in_atomic() || !mm)
	// 	goto no_context;

	/*
	 * As per x86, we may deadlock here.  However, since the kernel only
	 * validly references user space from well defined areas of the code,
	 * we can bug out early if this is from code which shouldn't.
	 */
	// if (!down_read_trylock(&mm->mmap_sem)) {
	// 	if (!user_mode(regs) && !search_exception_tables(regs->ARM_pc))
	// 		goto no_context;
	// 	down_read(&mm->mmap_sem);
	// } else {
	// 	/*
	// 	 * The above down_read_trylock() might have succeeded in
	// 	 * which case, we'll have missed the might_sleep() from
	// 	 * down_read()
	// 	 */
	// 	might_sleep();
// #ifdef CONFIG_DEBUG_VM
// 		if (!user_mode(regs) &&
// 		    !search_exception_tables(regs->ARM_pc))
// 			goto no_context;
// #endif
	// }

	fault = __do_page_fault(mm, addr, fsr, tsk);
	// up_read(&mm->mmap_sem);

	/*
	 * Handle the "normal" case first - VM_FAULT_MAJOR / VM_FAULT_MINOR
	 */
	if (!(fault & (VM_FAULT_ERROR | VM_FAULT_BADMAP | VM_FAULT_BADACCESS)))
		return 0;

	// if (fault & VM_FAULT_OOM) {
	// 	/*
	// 	 * We ran out of memory, call the OOM killer, and return to
	// 	 * userspace (which will retry the fault, or kill us if we
	// 	 * got oom-killed)
	// 	 */
	// 	pagefault_out_of_memory();
	// 	return 0;
	// }

	/*
	 * If we are in kernel mode at this point, we
	 * have no context to handle this fault with.
	 */
	if (!user_mode(regs))
		goto no_context;

	// if (fault & VM_FAULT_SIGBUS) {
	// 	/*
	// 	 * We had some memory, but were unable to
	// 	 * successfully fix up this page fault.
	// 	 */
	// 	sig = SIGBUS;
	// 	code = BUS_ADRERR;
	// } else {
	// 	/*
	// 	 * Something tried to access memory that
	// 	 * isn't in our memory map..
	// 	 */
	// 	sig = SIGSEGV;
	// 	code = fault == VM_FAULT_BADACCESS ?
	// 		SEGV_ACCERR : SEGV_MAPERR;
	// }

	__do_user_fault(tsk, addr, fsr, sig, code, regs);
	return 0;

no_context:
	__do_kernel_fault(mm, addr, fsr, regs);
#endif
	return 0;
}

static int do_translation_fault(unsigned long addr, unsigned int fsr,
		     struct pt_regs *regs)
{
	printf("this is %s(): %d\r\n", __func__, __LINE__);
#if 1
	unsigned int index;
	pgd_t *pgd, *pgd_k;
	pmd_t *pmd, *pmd_k;

	if (addr < TASK_SIZE)
		return do_page_fault(addr, fsr, regs);

	index = pgd_index(addr);

	/*
	 * FIXME: CP15 C1 is write only on ARMv3 architectures.
	 */
	pgd = cpu_get_pgd() + index;
	pgd_k = init_mm.pgd + index;

	if (pgd_none(*pgd_k))
		goto bad_area;

	if (!pgd_present(*pgd))
		set_pgd(pgd, *pgd_k);

	pmd_k = pmd_offset(pgd_k, addr);
	pmd   = pmd_offset(pgd, addr);

	if (pmd_none(*pmd_k))
		goto bad_area;

	copy_pmd(pmd, pmd_k);
	return 0;

bad_area:
	do_bad_area(addr, fsr, regs);
#endif
	return 0;
}

/*
 * Some section permission faults need to be handled gracefully.
 * They can happen due to a __{get,put}_user during an oops.
 */
static int do_sect_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
{
	printf("this is %s(): %d\r\n", __func__, __LINE__);

	do_bad_area(addr, fsr, regs);
	return 0;
}

/*
 * This abort handler always returns "fault".
 */
static int do_bad(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
{
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	return 1;
}

static struct fsr_info {
	int	(*fn)(unsigned long addr, unsigned int fsr, struct pt_regs *regs);
	int	sig;
	int	code;
	const char *name;
} fsr_info[] = {
	/*
	 * The following are the standard ARMv3 and ARMv4 aborts.  ARMv5
	 * defines these to be "precise" aborts.
	 */
	{ do_bad,		SIGSEGV, 0,		"vector exception"		   },
	{ do_bad,		SIGILL,	 BUS_ADRALN,	"alignment exception"		   },
	{ do_bad,		SIGKILL, 0,		"terminal exception"		   },
	{ do_bad,		SIGILL,	 BUS_ADRALN,	"alignment exception"		   },
	{ do_bad,		SIGBUS,	 0,		"external abort on linefetch"	   },
	{ do_translation_fault,	SIGSEGV, SEGV_MAPERR,	"section translation fault"	   },
	{ do_bad,		SIGBUS,	 0,		"external abort on linefetch"	   },
	{ do_page_fault,	SIGSEGV, SEGV_MAPERR,	"page translation fault"	   },
	{ do_bad,		SIGBUS,	 0,		"external abort on non-linefetch"  },
	{ do_bad,		SIGSEGV, SEGV_ACCERR,	"section domain fault"		   },
	{ do_bad,		SIGBUS,	 0,		"external abort on non-linefetch"  },
	{ do_bad,		SIGSEGV, SEGV_ACCERR,	"page domain fault"		   },
	{ do_bad,		SIGBUS,	 0,		"external abort on translation"	   },
	{ do_sect_fault,	SIGSEGV, SEGV_ACCERR,	"section permission fault"	   },
	{ do_bad,		SIGBUS,	 0,		"external abort on translation"	   },
	{ do_page_fault,	SIGSEGV, SEGV_ACCERR,	"page permission fault"		   },
	/*
	 * The following are "imprecise" aborts, which are signalled by bit
	 * 10 of the FSR, and may not be recoverable.  These are only
	 * supported if the CPU abort handler supports bit 10.
	 */
	{ do_bad,		SIGBUS,  0,		"unknown 16"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 17"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 18"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 19"			   },
	{ do_bad,		SIGBUS,  0,		"lock abort"			   }, /* xscale */
	{ do_bad,		SIGBUS,  0,		"unknown 21"			   },
	{ do_bad,		SIGBUS,  BUS_OBJERR,	"imprecise external abort"	   }, /* xscale */
	{ do_bad,		SIGBUS,  0,		"unknown 23"			   },
	{ do_bad,		SIGBUS,  0,		"dcache parity error"		   }, /* xscale */
	{ do_bad,		SIGBUS,  0,		"unknown 25"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 26"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 27"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 28"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 29"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 30"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 31"			   }
};

/*
 * Dispatch a data abort to the relevant handler.
 */
void do_DataAbort(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
{
	const struct fsr_info *inf = fsr_info + fsr_fs(fsr);
	// struct siginfo info;

	printf("this is %s(): %d	########### Data fault address = 0x%x ###########\r\n", __func__, __LINE__, addr);
	printf("this is %s(): %d	fsr = 0x%x\r\n", __func__, __LINE__, fsr);
	printf("this is %s(): %d	fsr_fs(fsr) = 0x%x\r\n", __func__, __LINE__, fsr_fs(fsr));

	if (!inf->fn(addr, fsr & ~FSR_LNX_PF, regs))
		return;

	printf("Unhandled fault: %s (0x%03x) at 0x%08lx\r\n",
		inf->name, fsr, addr);
	while (1);

	// info.si_signo = inf->sig;
	// info.si_errno = 0;
	// info.si_code  = inf->code;
	// info.si_addr  = (void __user *)addr;
	// arm_notify_die("", regs, &info, fsr, 0);
}

static struct fsr_info ifsr_info[] = {
	{ do_bad,		SIGBUS,  0,		"unknown 0"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 1"			   },
	{ do_bad,		SIGBUS,  0,		"debug event"			   },
	{ do_bad,		SIGSEGV, SEGV_ACCERR,	"section access flag fault"	   },
	{ do_bad,		SIGBUS,  0,		"unknown 4"			   },
	{ do_translation_fault,	SIGSEGV, SEGV_MAPERR,	"section translation fault"	   },
	{ do_bad,		SIGSEGV, SEGV_ACCERR,	"page access flag fault"	   },
	{ do_page_fault,	SIGSEGV, SEGV_MAPERR,	"page translation fault"	   },
	{ do_bad,		SIGBUS,	 0,		"external abort on non-linefetch"  },
	{ do_bad,		SIGSEGV, SEGV_ACCERR,	"section domain fault"		   },
	{ do_bad,		SIGBUS,  0,		"unknown 10"			   },
	{ do_bad,		SIGSEGV, SEGV_ACCERR,	"page domain fault"		   },
	{ do_bad,		SIGBUS,	 0,		"external abort on translation"	   },
	{ do_sect_fault,	SIGSEGV, SEGV_ACCERR,	"section permission fault"	   },
	{ do_bad,		SIGBUS,	 0,		"external abort on translation"	   },
	{ do_page_fault,	SIGSEGV, SEGV_ACCERR,	"page permission fault"		   },
	{ do_bad,		SIGBUS,  0,		"unknown 16"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 17"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 18"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 19"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 20"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 21"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 22"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 23"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 24"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 25"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 26"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 27"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 28"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 29"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 30"			   },
	{ do_bad,		SIGBUS,  0,		"unknown 31"			   },
};

void do_PrefetchAbort(unsigned long addr, unsigned int ifsr, struct pt_regs *regs)
{
	const struct fsr_info *inf = ifsr_info + fsr_fs(ifsr);
	// struct siginfo info;

	printf("this is %s(): %d	########### Prefetch fault address = 0x%x ###########\r\n", __func__, __LINE__, addr);
	printf("this is %s(): %d	ifsr = 0x%x\r\n", __func__, __LINE__, ifsr);
	printf("this is %s(): %d	fsr_fs(ifsr) = 0x%x\r\n", __func__, __LINE__, fsr_fs(ifsr));

	if (!inf->fn(addr, ifsr | FSR_LNX_PF, regs))
		return;

	printf("Unhandled prefetch abort: %s (0x%03x) at 0x%08lx\r\n",
		inf->name, ifsr, addr);
	while (1);

	// info.si_signo = inf->sig;
	// info.si_errno = 0;
	// info.si_code  = inf->code;
	// info.si_addr  = (void __user *)addr;
	// arm_notify_die("", regs, &info, ifsr, 0);
}
